<template>
  <el-dialog
    :title="title"
    :visible="visible"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    width="45%"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="formData" label-width="120px">
      <el-row style="margin-bottom: 10px;">
        <el-button type="success" @click="addItem">新增</el-button>
      </el-row>
      <el-form-item v-for="(item, index) in formData.Transmits" :key="index" :label="label" required>
        <template v-if="scheme.TransmitType == 4">
          <el-form-item
            :rules="[
              { required: true, message: '固定值不能为空!', trigger: 'blur' }
            ]"
          >
            <el-input v-model="item.Value" placeholder="固定值" maxlength="50" />
          </el-form-item>
        </template>
        <template v-else>
          <el-row :gutter="24" style="width: 700px;">
            <el-col :sm="8">
              <el-form-item
                :prop="'Transmits.'+index+'.BeginRange'"
                :rules="[
                  { required: true, message: '开始范围值不能为空!', trigger: 'blur' }
                ]"
              >
                <el-input-number v-model="item.BeginRange" :min="minNum" :max="maxNum" />
              </el-form-item>
            </el-col>
            <el-col :sm="1" style="text-align: center;">至</el-col>
            <el-col :sm="8">
              <el-form-item
                :prop="'Transmits.'+index+'.EndRange'"
                :rules="[
                  { validator: (rule, value, callback)=> checkEndValue(value,callback,item), trigger: 'blur' }
                ]"
              >
                <el-input-number v-model="item.EndRange" :min="minNum" :max="maxNum" />
              </el-form-item>
            </el-col>
            <el-col :sm="6">
              <el-button type="default" @click="deleteItem(index)">删除</el-button>
            </el-col>
          </el-row>
        </template>
      </el-form-item>
    </el-form>
    <el-row slot="footer" style="text-align:center;line-height:20px">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="default" @click="handleReset">重置</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import moment from 'moment'
import * as transmitApi from '@/api/transmit/transmit'
export default {
  props: {
    scheme: {
      type: Object,
      default: () => new {
        Id: null,
        SystemTypeId: null,
        RpcMerId: null,
        Scheme: null,
        TransmitType: null
      }()
    },
    server: {
      type: Object,
      default: () => new {
        ServerId: null,
        ServerName: null
      }()
    },
    id: {
      type: Number,
      default: 0
    },
    visible: {
      type: Boolean,
      required: true,
      default: false
    }
  },
  data() {
    return {
      minNum: 0,
      maxNum: 127,
      title: null,
      label: null,
      formData: {
        Transmits: []
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.formData.Transmits = []
          this.title = '服务节点(' + this.server.ServerName + ')负载均衡配置'
          if (this.scheme.TransmitType === 4) {
            this.label = '固定值'
          } else {
            this.label = '范围值'
            if (this.scheme.TransmitType === 1) {
              this.minNum = 48
              this.maxNum = 127
            } else if (this.scheme.TransmitType === 2) {
              this.minNum = -2147483648
              this.maxNum = 2147483647
            } else {
              this.minNum = null
              this.maxNum = null
            }
          }
          this.load()
        }
      },
      immediate: true
    }
  },
  mounted() {
  },
  methods: {
    moment,
    async load() {
      const list = await transmitApi.Get(this.id)
      const array = []
      if (this.scheme.TransmitType === 4) {
        list.forEach(c => {
          array.push({
            Value: c.Value
          })
        })
      } else {
        list.forEach(c => {
          c.Range.forEach(a => {
            array.push({
              BeginRange: a.BeginRange,
              EndRange: a.EndRange
            })
          })
        })
      }
      this.formData.Transmits = array
    },
    checkEndValue(value, callback, item) {
      if (value < item.BeginRange) {
        callback(new Error('结束值不能小于开始值!'))
        return
      }
      callback()
    },
    handleClose() {
      this.$emit('cancel', false)
    },
    deleteItem(index) {
      this.formData.Transmits.splice(index, 1)
    },
    checkRepeat() {
      const list = this.formData.Transmits
      for (let i = 0; i < list.length; i++) {
        const item = list[i]
        for (let k = 0; k < list.length; k++) {
          if (k !== i) {
            const other = list[k]
            if (this.scheme.TransmitType === 4) {
              if (item.Value === other.Value) {
                return true
              }
            } else if (item.BeginRange < other.EndRange && item.EndRange > other.BeginRange) {
              return true
            }
          }
        }
      }
      return false
    },
    addItem() {
      if (this.scheme.TransmitType === 4) {
        this.formData.Transmits.push({
          Value: null
        })
      } else {
        this.formData.Transmits.push({
          BeginRange: this.minNum,
          EndRange: this.maxNum
        })
      }
    },
    save() {
      if (this.formData.Transmits.length === 0) {
        this.$message({
          message: '配置项不能为空!',
          type: 'error'
        })
        return
      } else if (this.checkRepeat()) {
        this.$message({
          message: '配置值存在交集!',
          type: 'error'
        })
        return
      }
      const that = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          that.set()
        }
      })
    },
    async set() {
      let items
      if (this.scheme.TransmitType === 4) {
        items = this.formData.Transmits.map(c => {
          return {
            Value: c.Value
          }
        })
      } else {
        const list = this.formData.Transmits
        items = [
          {
            Range: list.map(c => {
              return {
                BeginRange: c.BeginRange,
                EndRange: c.EndRange
              }
            })
          }
        ]
      }
      await transmitApi.Set(this.id, items)
      this.$message({
        message: '配置成功！',
        type: 'success'
      })
      this.$emit('cancel', true)
    },
    handleReset() {
      this.formData = {
        Transmits: []
      }
      this.load()
    }
  }
}
</script>
